package com.cup.wx.config;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.servlet.HandlerInterceptor;

import com.cup.common.encryption.AESUtils;
import com.cup.wx.config.WebChatConfig.WXAccountProperties;
import com.cup.wx.micro.bean.AppletSession;
import com.cup.wx.micro.cache.SessionCache;

/**
 * 拦截器-实现
 * @author alan.zhao
 */
@EnableConfigurationProperties({WXAccountProperties.class})
public class AppletInterceptor implements HandlerInterceptor{ 
	
	private Logger logger = LoggerFactory.getLogger(AppletInterceptor.class);
	
	@Autowired
	private WXAccountProperties wxaccount;
	
    /** 
     * 进入controller层之前拦截请求 
     */  
	@Override
    public boolean preHandle(HttpServletRequest request, 
    		HttpServletResponse response, Object o) throws Exception {  
		
		String session = request.getHeader("session");
        
		logger.info("[{}]@session:[{}]", request.getRequestURI(), session);
        try {
        	
        	if(session != null && session != "") {
        		String[] sessionKey = AESUtils.decryptFromString(session, wxaccount.getAeskey()).split("@");
        		AppletSession applet = new AppletSession();
        		applet.setOpenid(sessionKey[0]);
        		applet.setSessionKey(sessionKey.length > 1 ? sessionKey[1] : null);
        		applet.setUinionid(sessionKey.length > 2 ? sessionKey[2] : null);
        		
        		SessionCache.getIntance().put(applet);
        	}
        	
			return true;
		}catch (Exception e) {
			return false;
		}
  
    }  
	
	@Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) throws Exception {  
		SessionCache.getIntance().remove();
    } 
}  

